package com.erp.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author lpy
 * 登录权限过滤器:对于没有登录的用户,只能访问登录注册页面
 */
@WebFilter({"*.jsp","*.action"})
public class AuthorFilter implements Filter {
    /**
     * 没有登录就可以访问的页面
     */
    private String[] unLoginPages = {"/login.jsp","/login.action","/image.jsp"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("登录权限过滤器初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取request、response、session对象
        HttpServletRequest request = ((HttpServletRequest)servletRequest);
        HttpServletResponse response = ((HttpServletResponse)servletResponse);
        HttpSession session = ((HttpServletRequest) servletRequest).getSession();
        //获取请求servlet地址
        String servletPath = request.getServletPath();
        //定义一个标记,表示是否要对请求页面进行拦截处理
        boolean flag = false;
        for (String page:unLoginPages){
            if (page.equals(servletPath)){
                flag = true;
            }
        }

        if (flag){
            //如果是登录或注册页面不进行拦截
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            //从session中获取保存的user信息 判断用户是否已经登录
            Object user = session.getAttribute("currentUser");
            if (user==null){
                response.sendRedirect("login.jsp");
            }else{
                //用户已经登录过了
                filterChain.doFilter(servletRequest,servletResponse);
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("登录权限过滤器销毁了");
    }
}
